package com.shishi.fast.generator.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shishi.fast.common.exception.ApiException;
import com.shishi.fast.common.util.DateTimeUtils;
import com.shishi.fast.common.vo.ResultCode;
import com.shishi.fast.generator.domain.DeviceDO;
import com.shishi.fast.generator.domain.DeviceMaintainDO;
import com.shishi.fast.generator.domain.DeviceTemplateDO;
import com.shishi.fast.generator.excel.DeviceMaintainImportExcel;
import com.shishi.fast.generator.mapper.DeviceMaintainMapper;
import com.shishi.fast.generator.mapper.DeviceMapper;
import com.shishi.fast.generator.mapper.DeviceTemplateMapper;
import com.shishi.fast.generator.service.DeviceMaintainService;
import com.shishi.fast.generator.vo.DeviceMaintainRequest;
import com.shishi.fast.generator.vo.TemplateResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class DeviceMaintainServiceImpl extends ServiceImpl<DeviceMaintainMapper, DeviceMaintainDO> implements DeviceMaintainService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceMaintainMapper deviceMaintainMapper;

    @Autowired
    private DeviceTemplateMapper deviceTemplateMapper;

    @Override
    public void generateData(DeviceMaintainRequest.GenerateDataParam param) {
        List<DeviceDO> deviceDOList = deviceMapper.selectList(Wrappers.<DeviceDO>lambdaQuery()
                .eq(DeviceDO::getCompanyId, param.getCompanyId())
                .eq(DeviceDO::getDeleted, 0)
        );

        for (DeviceDO deviceDO : deviceDOList) {
            List<DeviceMaintainDO> list = generateMaintenanceData(param.getStartDate(), param.getEndDate(), deviceDO.getMaintainType(), deviceDO);
            this.saveBatch(list);
        }
    }

    @Override
    public void importExcel(MultipartFile file, String companyId) {
        ImportParams params = new ImportParams();

        List<DeviceMaintainImportExcel> importExcelList = new ArrayList<>();
        try {
            importExcelList = ExcelImportUtil.importExcel(file.getInputStream(), DeviceMaintainImportExcel.class, params);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (ObjectUtils.isEmpty(importExcelList)) {
            throw new ApiException(ResultCode.FAILED);
        }

        int count = 0;
        for (DeviceMaintainImportExcel excel : importExcelList) {
            count++;
            DeviceDO deviceDO = deviceMapper.selectOne(Wrappers.<DeviceDO>lambdaQuery()
                    .eq(DeviceDO::getCompanyId, companyId)
                    .eq(DeviceDO::getDeviceNo, excel.getDeviceNo())
            );
            if (ObjectUtils.isEmpty(deviceDO)) {
                throw new ApiException(ResultCode.FAILED);
            }

            DeviceMaintainDO deviceMaintainDO = new DeviceMaintainDO();
            BeanUtils.copyProperties(excel, deviceMaintainDO);

            //固定参数
            deviceMaintainDO.setCompanyId(companyId);
            deviceMaintainDO.setDeviceId(deviceDO.getId());

            //加工点检内容
            List<Map<String, Object>> mapList = new ArrayList<>();

            Map<String, Object> map2 = new HashMap<>();
            map2.put("title", "一级保养");
            map2.put("checked", "true");
            mapList.add(map2);

            if (excel.getMaintainStatus().equals("已完成")) {
                deviceMaintainDO.setMaintainStatus(1);
            } else {
                deviceMaintainDO.setMaintainStatus(0);
            }

            deviceMaintainDO.setCreateTime(excel.getStartTime());
            deviceMaintainDO.setMaintainContent(JSONObject.toJSONString(mapList));
            deviceMaintainDO.setUpdateTime(excel.getStartTime());

            deviceMaintainMapper.insert(deviceMaintainDO);
        }
    }

    public List<DeviceMaintainDO> generateMaintenanceData(String startDateStr, String endDateStr, boolean isPeriodic, DeviceDO deviceDO) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        Date startDate = null;
        Date endDate = null;
        try {
            startDate = dateFormat.parse(startDateStr + " 08:00");
            endDate = dateFormat.parse(endDateStr + " 18:00");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        //查询模版，如果模版为空则报错
        DeviceTemplateDO deviceTemplateDO = deviceTemplateMapper.selectById(deviceDO.getMaintainTemplateId());
        if (ObjectUtils.isEmpty(deviceTemplateDO)) {
            throw new ApiException(ResultCode.FAILED, "未查询到设备绑定的保养模版");
        }

        List<DeviceMaintainDO> deviceMaintainDOList = new ArrayList<>();

        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);

        while (cal.getTime().before(endDate)) {
            DeviceMaintainDO deviceMaintainDO = new DeviceMaintainDO();

            deviceMaintainDO.setCompanyId(deviceDO.getCompanyId());
            deviceMaintainDO.setDeviceId(deviceDO.getId());
            deviceMaintainDO.setMaintainNo(UUID.randomUUID().toString());

            //获取模版内容
            List<TemplateResponse.TemplateContent> templateContentList = JSONArray.parseArray(deviceTemplateDO.getTemplateContent(), TemplateResponse.TemplateContent.class);
            //存入结果
            List<TemplateResponse.TemplateResult> templateResultList = new ArrayList<>();
            for (TemplateResponse.TemplateContent templateContent : templateContentList) {
                TemplateResponse.TemplateResult templateResult = new TemplateResponse.TemplateResult();
                BeanUtils.copyProperties(templateContent, templateResult);
                templateResult.setChecked("true");
                templateResultList.add(templateResult);
            }
            //转换字符串存入对象
            deviceMaintainDO.setMaintainContent(JSONObject.toJSONString(templateResultList));

            deviceMaintainDO.setMaintainStatus(1);

            Date maintenanceStartTime = DateTimeUtils.getRandomTime(cal.getTime(), 8, 10);
            Date maintenanceEndTime = DateTimeUtils.getRandomEndTime(maintenanceStartTime, 1, 2);

            Random random = new Random();
            int randomNumber = random.nextInt(5) + 1;

            deviceMaintainDO.setStartTime(maintenanceStartTime);
            deviceMaintainDO.setStartBy("管理员" + randomNumber);
            deviceMaintainDO.setEndTime(maintenanceEndTime);
            deviceMaintainDO.setEndBy("管理员" + randomNumber);

            deviceMaintainDO.setCreateBy("管理员" + randomNumber);
            deviceMaintainDO.setCreateTime(maintenanceStartTime);
            deviceMaintainDO.setUpdateTime(maintenanceEndTime);
            deviceMaintainDO.setDeleted(0);

            deviceMaintainDOList.add(deviceMaintainDO);

            if (isPeriodic) {
                cal.add(Calendar.DATE, deviceDO.getMaintainCycle()); // 按周期生成
            } else {
                break; // 只生成一次
            }
        }
        return deviceMaintainDOList;
    }

}




